const express = require('express');
const router = express.Router();

// 导入工具和中间件
const { success, error, badRequest, asyncHandler, paginated } = require('../utils/response');
const { optionalAuth } = require('../utils/auth');

// 导入服务层
const homeService = require('../services/homeService');

/**
 * 获取轮播图
 * GET /home/banners
 */
router.get('/banners', asyncHandler(async (req, res) => {
  const banners = await homeService.getBanners();
  success(res, banners);
}));

/**
 * 获取功能模块
 * GET /home/functions
 */
router.get('/functions', asyncHandler(async (req, res) => {
  const modules = await homeService.getFunctionModules();
  success(res, modules);
}));

/**
 * 获取推荐内容
 * GET /home/recommendations
 */
router.get('/recommendations', optionalAuth, asyncHandler(async (req, res) => {
  const userId = req.user ? req.user.id : null;
  const result = await homeService.getRecommendations(req.query, userId);
  paginated(res, result.list, result.total, result.page, result.limit);
}));

/**
 * 获取活动列表
 * GET /home/activities
 */
router.get('/activities', asyncHandler(async (req, res) => {
  const activities = await homeService.getActivities();
  success(res, activities);
}));

/**
 * 获取精选推荐
 * GET /home/featured
 */
router.get('/featured', optionalAuth, asyncHandler(async (req, res) => {
  const userId = req.user ? req.user.id : null;
  const result = await homeService.getRecommendations({ page: 1, limit: 5 }, userId);
  success(res, result.list);
}));

/**
 * 获取首页统计数据
 * GET /home/statistics
 */
router.get('/statistics', optionalAuth, asyncHandler(async (req, res) => {
  const userId = req.user ? req.user.id : null;
  const statistics = await homeService.getHomeStats(userId);
  success(res, statistics);
}));

/**
 * 增加推荐内容查看次数
 * POST /home/recommendations/:id/view
 */
router.post('/recommendations/:id/view', optionalAuth, asyncHandler(async (req, res) => {
  const { id } = req.params;
  const userId = req.user ? req.user.id : null;

  try {
    await homeService.recordRecommendationView(parseInt(id), userId);
    success(res, null, '查看次数已更新');
  } catch (err) {
    return badRequest(res, err.message);
  }
}));

module.exports = router;
